<?php
class OrderModel extends Model {

    public function __construct() {
        parent::__construct();
        $this->tables = array(DB_FREFIX.'order');
        $this->fields = array('id','user','name','email','address','zipcode','phone','building','delivery','pay','price','text','ps','ordernum','goods','date','order_state','order_pay','order_delivery','delivery_name','delivery_url','delivery_number','refund');
        $this->check = new OrderCheck();
        list(
            $this->R['id'],
            $this->R['user'],
            $this->R['orderid']
        ) = $this->getRequest()->getParams(array(
            isset($_GET['id']) ? $_GET['id'] : null,
            isset($_COOKIE['user']) ? $_COOKIE['user'] : null,
            isset($_GET['orderid']) ? $_GET['orderid'] : null
            )
        );
    }

    public function findAll() {
        return parent::select($this->tables,$this->fields,array('limit'=>$this->limit,'order'=>'date DESC'));
    }

    public function findUserAllOrder() {
        return parent::select($this->tables,array('id','ordernum','date','price','order_state','order_pay','order_delivery','refund'),array('where'=>array('user='.$this->R['user']),'limit'=>$this->limit,'order'=>'date DESC'));
    }

    public function findCommendOrder() {
        $condition = array('id='.$this->R['orderid']);
        $order = parent::select($this->tables,array('goods'),array('where'=>$condition));
        $goods = unserialize(htmlspecialchars_decode($order[0]->goods));
        $oenGoods = unserialize($goods[$_GET['goodsid']]);
        return $oenGoods;
    }

    public function update() {
        $condition = array('id='.$this->R['id']);
        $updateData = $this->getRequest()->filter($this->fields);
        if(!isset($updateData['refund'])) $updateData['refund'] = '';
        if(!isset($updateData['order_state'])) $updateData['refund'] = '';
        if($updateData['order_state'] == '已取消' || $updateData['refund'] == 2) {
            $goods = array();
            $sorder = parent::select($this->tables,array('goods'),array('where'=>$condition));
            $orderGoods = unserialize(htmlspecialchars_decode($sorder[0]->goods));
            $this->tables = array(DB_FREFIX.'goods');
            foreach($orderGoods as $key=>$value) {
                $temp = unserialize($value);
                $goods[$key] = $temp['num'];
            }
            foreach($goods as $key=>$value) {
                $condition2 = array("id='$key'");
                $updateData2['inventory'] = array('inventory+'.$value);
                parent::update($updateData2,$condition2);
            }
            $this->tables = array(DB_FREFIX.'order');
        }
        if($updateData['refund'] == '2') $updateData['refund_date'] = Tool::getDate();
        //增加成交记录
        if($updateData['order_pay'] == '已付款') $this->record();
        return parent::update($updateData,$condition);
    }

    public function delete() {
        $condition = array('id='.$this->R['id']."AND order_state = '已取消'");
        if(!$this->check->isHasCancel($this,$condition)) $this->check->displayError();
        return parent::delete($condition);
    }

    public function total() {
        //如果是前台，则把当前用户订单列举出来，如果是后台就把所有用户的订单列出来
        if(isset($_COOKIE['user']) && $_GET['a'] == 'member' && $_GET['m'] == 'order') {
           return parent::total(array('where'=>array('user='.$this->R['user'])));
        } else {
            return parent::total();
        }
    }

    public function findOrderDeatails() {
        $oneOrder = parent::select($this->tables,array('id','ordernum','goods','delivery','pay','price','text','ps','order_state','order_pay','order_delivery','delivery_name','delivery_url','delivery_number','refund','date','name','email','user','zipcode','phone','building','address'),array('where'=>array('id='.$this->R['id'])));
        if(isset($oneOrder[0]->goods)) {
            $oneOrder[0]->goods = unserialize(htmlspecialchars_decode($oneOrder[0]->goods));
            foreach($oneOrder[0]->goods as $key=>$value) {
                $oneOrder[0]->goods[$key] = unserialize($value);
            }
        }
        return $oneOrder;
    }

    public function order() {
        $orderDate = $this->getRequest()->filter($this->fields);
        $orderDate['date'] = Tool::getDate();
        $orderDate['ordernum'] = Tool::getOrderNum();
        $orderDate['goods'] = serialize($_COOKIE['cart']);
        return parent::add($orderDate);
    }

    public function alipay($num) {
        $updateData['order_pay'] = '已付款';
        $condition = array("ordernum='$num'");
        return parent::update($updateData,$condition);
    }

    public function clear() {
        $condition = array("HOUR(TIMEDIFF(NOW(),date)) > 24 AND order_state='未确认' AND order_pay='未付款' AND order_delivery='未发货'");
        $goods = parent::select($this->tables,array('goods'),array('where'=>$condition));
        $this->tables = array(DB_FREFIX.'goods');
        foreach($goods as $key=>$value) {
            $temp = unserialize(htmlspecialchars_decode($value->goods));
            foreach($temp as $key=>$value) {
                $condition2 = array("id='$key'");
                $t2 = unserialize($value);
                parent::update(array('inventory'=>array('inventory+'.$t2['num'])),$condition2);
            }
        }
        $this->tables = array(DB_FREFIX.'order');
        return parent::delete($condition);
    }

    public function cancel() {
        $condition = array('id='.$this->R['id']);
        $goods = parent::select($this->tables,array('goods'),array('where'=>$condition));
        $goods = unserialize(htmlspecialchars_decode($goods[0]->goods));
        $this->tables = array(DB_FREFIX.'goods');
        foreach($goods as $key=>$value) {
            $temp = unserialize($value);
            $condition2 = array("id='$key'");
            parent::update(array('inventory'=>array('inventory+'.$temp['num'])),$condition2);
        }
        $this->tables = array(DB_FREFIX.'order');
        $updateData['order_state'] = '已取消';
        return parent::update($updateData,$condition);
    }

    public function refund() {
        $condition = array('id='.$this->R['id']."AND order_pay='已付款'");
        $updateData['refund'] = 1;
        return parent::update($updateData,$condition);
    }

    public function reOrder() {
        $condition = array('id='.$this->R['id']);
        $goods = parent::select($this->tables,array('goods'),array('where'=>$condition));
        $goods = unserialize(htmlspecialchars_decode($goods[0]->goods));
        $this->tables = array(DB_FREFIX.'goods');
        foreach($goods as $key=>$value) {
            $temp = unserialize($value);
            $condition2 = array("id='$key'");
            $obj = parent::select($this->tables,array('inventory'),array('where'=>$condition2));
            $inventory = $obj[0]->inventory;
            if($inventory < $temp['num']) return 404; //判断重新下单时的库存是否足够，不足够则退出循环，返回错误信息
        }
        foreach($goods as $key=>$value) {
            $temp = unserialize($value);
            $condition2 = array("id='$key'");
            parent::update(array('inventory'=>array('inventory-'.$temp['num'])),$condition2);
        }
        $this->tables = array(DB_FREFIX.'order');
        $updateData['refund'] = 0;
        $updateData['order_state'] = '未确认';
        $updateData['order_pay'] = '未付款';
        $updateData['order_delivery'] = '未发货';
        $updateData['delivery_name'] = '';
        $updateData['delivery_url'] = '';
        $updateData['delivery_number'] = '';
        $updateData['date'] = Tool::getDate();
        return parent::update($updateData,$condition);
    }

    public function clearNotReOrder() {
        $condition = array('HOUR(TIMEDIFF(NOW(),date)) > 24 AND refund=2');
        $updateData['order_state'] = '已取消';
        parent::update($updateData,$condition);
    }

    public function nextId() {
        return parent::nextId($this->tables[0]);
    }

    public function isCart() {
        if(!$this->check->isCart()) $this->check->displayError();
        return true;
    }

    //判断是否可以正确评论
    public function isCommend() {
        $condition = array('id='.$this->R['orderid']);
        $order = parent::select($this->tables,array('order_delivery'),array('where'=>$condition));
        if(!$this->check->isPostGooods($order[0]->order_delivery)) $this->check->displayError();
    }

    //成交记录
    public function record() {
        $condition = array('id='.$this->R['id']);
        $sorder = parent::select($this->tables,array('goods'),array('where'=>$condition));
        $orderGoods = unserialize(htmlspecialchars_decode($sorder[0]->goods));
        $this->tables = array(DB_FREFIX.'record');
        foreach($orderGoods as $key=>$value) {
            $temp = unserialize($value);
            $addData['goodsid'] = $temp['id'];
            $addData['name'] = $temp['name'];
            $addData['user'] = $_POST['user'];
            $addData['num'] = $temp['num'];
            $addData['price'] = $temp['price_sale'];
            $addData['date'] = Tool::getDate();
            $addData['attr'] = '';
            foreach($temp['attr'] as $key2=>$value2) {
                $addData['attr'] .= $key2.':';
                foreach($value2 as $value3) {
                    $addData['attr'] .= $value3.',';
                }
            }
            $addData['attr'] = mb_substr($addData['attr'],0,-1,'utf-8').';';
            parent::add($addData);
        }
        $this->tables = array(DB_FREFIX.'order');
    }
}
?>